

// npm install express --save
// npm install ejs --save

var fs = require('fs');
var express = require("express");
var bodyParser = require('body-parser');
const multer = require('multer');
const path = require('path');
const { url } = require('inspector');
var app = express();

app.use(bodyParser.json());
app.use((req, res, next) => {
	res.header('Access-Control-Allow-Origin', '*'); // 允许所有来源
	res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE'); // 允许的方法
	  res.header('Access-Control-Allow-Headers', 'Content-Type, transformrequest'); // 允许的头
	next();
});
// app.options('/shop/uploadImgMultiple', jfum.optionsHandler.bind(jfum));
// app.use(express.bodyParser());


app.get('/static/abcd.png', function (req, res) {
	res.sendFile(__dirname + '/imgs/abcd.png');
});

//获取静态资源
app.get('/static/*', function (req, res) {
	let target = req.path.substring(8);
	// console.log(target);
	// let target = req.query.path.substring(8);	//截取/static/后面的内容
	let path = __dirname + '/imgs/' + target;
	if (fs.existsSync(path))
		res.sendFile(path);
	else
		res.status(404).send('sorry, cannot find the file');
});


//get请求首页信息
app.get('/api/food/index',function (req,res) {
    console.log(req.query);
	fs.readFile('index.json', 'utf-8', function (err, data) {
	    if (err) {
	        console.log(err);
	    } else {
            res.writeHead(200,{'Content-Type':'application/json;charset=utf-8'});
	        //res.end(data);
	        res.end(data);
	    }
	});
});

//get请求菜单列表
app.get('/api/food/list',function (req,res) {
    console.log(req.query);
	fs.readFile('list.json', 'utf-8', function (err, data) {
	    if (err) {
	        console.log(err);
	    } else {
            res.writeHead(200,{'Content-Type':'application/json;charset=utf-8'});
	        //res.end(data);
	        res.end(data);
	    }
	});
});
//get请求订单列表
app.get('/api/food/orderlist',function (req,res) {
    console.log(req.query);
	console.log(req.query.last_id);

	var filename = 'orderlist-0.json';

   if (req.query.last_id === '10')  {
    	// 10 : 11~20
		filename = 'orderlist-10.json';
		console.log('filename is orderlist-10.json');
    }else if (req.query.last_id === '20')  {
    	// 20: 21~30
		filename = 'orderlist-20.json';
		console.log('filename is orderlist-20.json');
    }

	fs.readFile(filename, 'utf-8', function (err, data) {
	    if (err) {
	        console.log(err);
	    } else {
            res.writeHead(200,{'Content-Type':'application/json;charset=utf-8'});
	        //res.end(data);
	        res.end(JSON.stringify(JSON.parse(data)));
	    }
	});
});



//订单请求post
app.post("/api/food/order",function(req,res){
   res.json({error:0,order_id:3})
});



app.get("/api/food/order",function(req,res){
   fs.readFile('order.json', 'utf-8', function (err, data) {
	    if (err) {
	        console.log(err);
	    } else {
            res.writeHead(200,{'Content-Type':'application/json;charset=utf-8'});
	        //res.end(data);
	        // res.end(JSON.stringify(JSON.parse(data)[0]));
	        // 因为搭建服务器比较麻烦，这里采用模拟数据
	         res.end(JSON.stringify(JSON.parse(data)[0])); // 表示未取餐
	         // res.end(JSON.stringify(JSON.parse(data)[2])); 表示已取餐
	    }
	});
});


//支付post请求
app.post("/api/food/pay",function(req,res){
   res.json({error:0,order_id:3})
});

//get请求消费记录
app.get('/api/food/record',function (req,res) {
    console.log(req.query);
	fs.readFile('record.json', 'utf-8', function (err, data) {
	    if (err) {
	        console.log(err);
	    } else {
            res.writeHead(200,{'Content-Type':'application/json;charset=utf-8'});
	        //res.end(data);
	        res.end(data);
	    }
	});
});

//get请求商店数据
app.get('/api/shop/shop_data',function (req,res) {
    console.log(req.query);
	fs.readFile('shop_data.json', 'utf-8', function (err, data) {
	    if (err) {
	        console.log(err);
	    } else {
            res.writeHead(200,{'Content-Type':'application/json;charset=utf-8'});
	        //res.end(data);
	        res.end(data);
	    }
	});
});

// const upload = multer({ dest: 'foods/' });

// 配置存储选项
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'imgs/foods/') // 文件保存目录（需提前创建）
  },
  filename: (req, file, cb) => {
    // 生成唯一文件名（原始名+时间戳+后缀）
    // const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
    cb(null, file.fieldname + '-' + file.originalname)
  }
})
const upload = multer({ storage: storage })

// 单文件上传
app.post("/shop/uploadImg", upload.single('image'), (req,res)=>{

	console.log("上传图片成功，图片保存在：foods/"+req.file.filename);
	let path = "http://localhost:8082/static/foods/" + req.file.filename;
	res.json({
		data: {
			url: path
		}
	});
});

// const upload2 = multer({
//     dest:"imgs/foods/" })
// 多文件上传
app.post('/shop/uploadImgMultiple', upload.array('images'), (req, res) => {
	// console.log('req.files: ', req.file);
	console.log('req.files: ', req.files);
	let paths = [];
    for (let i = 0; i < req.files.length; i++)
	{
		console.log("上传图片成功，图片保存在：foods/"+req.files[i].filename);
		paths.push("http://localhost:8082/static/foods/" + req.files[i].filename);
	}
	res.json({
		data: {
			urls: paths
		}
	});
});

console.log("server is running at http://localhost:8082");
app.listen(8082);



/*

//模板引擎
app.set("view engine","ejs");

app.get("/",function(req,res){
     res.render("form");
});
/*
//bodyParser API
app.use(bodyParser.urlencoded({ extended: false }));

app.post("/",function(req,res){
    console.log(req.body);
});

*/
